<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="50%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef" v-loading="dataLoading"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>

      <el-form-item label="消费券：" prop="id">
        <span>{{ couponData.title }}</span>
      </el-form-item>

      <el-form-item label="赠送用户：" prop="user_ids">
        <SelectRemote v-model="selectAccount" api-url="/search/user/list" placeholder="请输入用户账号进行选择" @change="handleSelectChange" style="margin-bottom: 8px;width: 60%"/>
        <el-select v-model="formData.user_ids" multiple>
          <el-option v-for="item in selectList" :key="item.id" :label="item.label1" :value="item.id"/>
        </el-select>
      </el-form-item>

    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['coupon:config:give_away']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { SelectRemote } from '@/components/other';
import { SelectItem } from '@/api';
import { Coupon, couponGiveAway } from '@/api/api-coupon.ts';

defineOptions({name: 'coupon-give-away-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

interface CouponGiveAway {
  id: number
  user_ids: number[];
}

/** 默认表单数据 */
const defaultForm: CouponGiveAway = <CouponGiveAway>{id: 0, user_ids: []};

// 表单数据
const formData = ref({...defaultForm});

/** 默认表单数据 */
const defCoupon: Coupon = <Coupon>{id: 0};
// 表单数据
const couponData = ref({...defCoupon});

// 表单验证规则
const formRules = reactive<FormRules>({
  user_ids: [{required: true, message: '请选择用户', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})


/** 打开弹窗 */
const open = async (item: any) => {
  dialogTitle.value = '消费券赠送';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
  // 设置值
  couponData.value = item;
  formData.value.id = item.id;
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    console.log(formData.value)
    if (!valid) {
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })

    // 提交数据
    couponGiveAway(formData.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  selectList.value = [];
  selectAccount.value = undefined;
  // 重置表单数据
  formData.value = {...defaultForm};
  formData.value.user_ids = [];
  couponData.value = {...defCoupon};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 用户选择被改变 */
const selectList = ref<SelectItem[]>([]);
const selectAccount = ref();
const handleSelectChange = (val: any) => {
  if (val && val.id && !selectList.value.find(it => it.id == val.id)) {
    formData.value.user_ids.push(val.id);
    selectList.value.push(val);
  }
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
